<template>
  <div class="study-charts">
    <!-- 学习时间分布分析 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>学习时间分布（科目饼图）</span>
              <el-tag type="info">资产类-流动资产</el-tag>
            </div>
          </template>
          <div ref="timeDistributionChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>学习时间趋势图</span>
              <el-tag type="success">资产类-流动资产</el-tag>
            </div>
          </template>
          <div ref="timeTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 效率分析（损益类） -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>学习效率K线图</span>
              <el-tag type="warning">损益类-效率分析</el-tag>
            </div>
          </template>
          <div ref="efficiencyKLineChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>效率变化曲线</span>
              <el-tag type="warning">损益类-效率分析</el-tag>
            </div>
          </template>
          <div ref="efficiencyTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 知识资产分析（固定资产类） -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>知识资产雷达图</span>
              <el-tag type="primary">资产类-固定资产</el-tag>
            </div>
          </template>
          <div ref="knowledgeRadarChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>知识资产价值分析</span>
              <el-tag type="primary">资产类-固定资产</el-tag>
            </div>
          </template>
          <div ref="assetValueChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 投入产出分析（所有者权益类） -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>投入产出分析</span>
              <el-tag type="success">所有者权益-知识资本</el-tag>
            </div>
          </template>
          <div ref="inputOutputChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>学习债务分析</span>
              <el-tag type="danger">负债类-学习债务</el-tag>
            </div>
          </template>
          <div ref="debtAnalysisChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 财务报表可视化 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>学习财务报表总览</span>
              <el-tag type="info">综合财务分析</el-tag>
            </div>
          </template>
          <div ref="financialOverviewChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { studyApi } from '@/api/study'

export default {
  name: 'StudyCharts',
  props: {
    userId: {
      type: Number,
      required: true
    }
  },
  setup(props) {
    // 图表引用
    const timeDistributionChart = ref(null)
    const timeTrendChart = ref(null)
    const efficiencyKLineChart = ref(null)
    const efficiencyTrendChart = ref(null)
    const knowledgeRadarChart = ref(null)
    const assetValueChart = ref(null)
    const inputOutputChart = ref(null)
    const debtAnalysisChart = ref(null)
    const financialOverviewChart = ref(null)
    
    // 图表实例
    let chartInstances = {}
    
    const loadChartData = async () => {
      if (!props.userId) return
      
      try {
        // 获取最近30天的数据
        const endDate = new Date()
        const startDate = new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000)
        
        // 模拟数据（实际应该从API获取）
        const mockData = generateMockData()
        
        // 初始化所有图表
        initTimeDistributionChart(mockData.timeBySubject)
        initTimeTrendChart(mockData.dailyTrend)
        initEfficiencyKLineChart(mockData.efficiencyData)
        initEfficiencyTrendChart(mockData.dailyTrend)
        initKnowledgeRadarChart(mockData.knowledgeAssets)
        initAssetValueChart(mockData.assetValues)
        initInputOutputChart(mockData.inputOutput)
        initDebtAnalysisChart(mockData.debtData)
        initFinancialOverviewChart(mockData.financialData)
        
      } catch (error) {
        console.error('加载图表数据失败:', error)
      }
    }
    
    // 生成模拟数据
    const generateMockData = () => {
      return {
        timeBySubject: [
          { name: 'Java编程', value: 45.5 },
          { name: '数据结构', value: 32.8 },
          { name: 'Vue.js', value: 15.2 },
          { name: '英语', value: 28.5 },
          { name: '机器学习', value: 18.5 }
        ],
        dailyTrend: Array.from({ length: 30 }, (_, i) => {
          const date = new Date()
          date.setDate(date.getDate() - 29 + i)
          return [
            date.toISOString().split('T')[0],
            Math.random() * 8 + 2 // 2-10小时
          ]
        }),
        efficiencyData: Array.from({ length: 30 }, (_, i) => {
          const date = new Date()
          date.setDate(date.getDate() - 29 + i)
          const base = 1.0
          const variation = (Math.random() - 0.5) * 0.4
          return [
            date.toISOString().split('T')[0],
            [base + variation - 0.1, base + variation, base + variation + 0.1, base + variation]
          ]
        }),
        knowledgeAssets: {
          subjects: ['Java编程', '数据结构', 'Vue.js', '英语', '机器学习'],
          mastery: [75, 65, 45, 55, 40],
          values: [2151.25, 1548.00, 722.00, 1338.75, 878.75]
        },
        assetValues: [
          { name: 'Java编程', value: 2151.25, growth: 12.5 },
          { name: '数据结构', value: 1548.00, growth: 8.3 },
          { name: 'Vue.js', value: 722.00, growth: 15.2 },
          { name: '英语', value: 1338.75, growth: 5.8 },
          { name: '机器学习', value: 878.75, growth: 18.7 }
        ],
        inputOutput: {
          dates: Array.from({ length: 30 }, (_, i) => {
            const date = new Date()
            date.setDate(date.getDate() - 29 + i)
            return date.toISOString().split('T')[0]
          }),
          input: Array.from({ length: 30 }, () => Math.random() * 6 + 2),
          output: Array.from({ length: 30 }, () => Math.random() * 8 + 3)
        },
        debtData: [
          { name: '未完成计划', value: 4095.00, type: '学习债务' },
          { name: '逾期计划', value: 6825.00, type: '时间负债' },
          { name: '拖延时间', value: 1200.00, type: '时间负债' }
        ],
        financialData: {
          assets: 5760.00,
          liabilities: 10920.00,
          equity: -5160.00,
          income: 698.34,
          cost: 821.50,
          profit: -123.16
        }
      }
    }
    
    // 1. 学习时间分布饼图（流动资产）
    const initTimeDistributionChart = (data) => {
      if (!timeDistributionChart.value) return
      
      chartInstances.timeDistribution = echarts.init(timeDistributionChart.value)
      
      const option = {
        title: {
          text: '学习时间分布',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}小时 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            name: '学习时间',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: true,
              formatter: '{b}: {c}h'
            }
          }
        ],
        color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
      }
      
      chartInstances.timeDistribution.setOption(option)
    }
    
    // 2. 学习时间趋势图（流动资产）
    const initTimeTrendChart = (data) => {
      if (!timeTrendChart.value) return
      
      chartInstances.timeTrend = echarts.init(timeTrendChart.value)
      
      const dates = data.map(item => item[0])
      const hours = data.map(item => item[1])
      
      const option = {
        title: {
          text: '每日学习时长趋势',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '日期: {b}<br/>学习时长: {c}小时'
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: { rotate: 45 }
        },
        yAxis: {
          type: 'value',
          name: '学习时长(小时)',
          min: 0
        },
        series: [
          {
            name: '每日学习时长',
            type: 'line',
            data: hours,
            smooth: true,
            lineStyle: { color: '#5470c6', width: 3 },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
                { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
              ])
            },
            markLine: {
              data: [
                { type: 'average', name: '平均值' }
              ]
            }
          }
        ]
      }
      
      chartInstances.timeTrend.setOption(option)
    }
    
    // 3. 学习效率K线图（损益类）
    const initEfficiencyKLineChart = (data) => {
      if (!efficiencyKLineChart.value) return
      
      chartInstances.efficiencyKLine = echarts.init(efficiencyKLineChart.value)
      
      const dates = data.map(item => item[0])
      const klineData = data.map(item => item[1])
      
      const option = {
        title: {
          text: '学习效率K线图',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: { rotate: 45 }
        },
        yAxis: {
          type: 'value',
          name: '效率评分',
          min: 0.5,
          max: 1.5
        },
        series: [
          {
            name: '效率K线',
            type: 'candlestick',
            data: klineData,
            itemStyle: {
              color: '#ec0000',
              color0: '#00da3c',
              borderColor: '#8A0000',
              borderColor0: '#008F28'
            }
          }
        ]
      }
      
      chartInstances.efficiencyKLine.setOption(option)
    }
    
    // 4. 效率变化曲线（损益类）
    const initEfficiencyTrendChart = (data) => {
      if (!efficiencyTrendChart.value) return
      
      chartInstances.efficiencyTrend = echarts.init(efficiencyTrendChart.value)
      
      const dates = data.map(item => item[0])
      const efficiency = data.map(() => Math.random() * 0.4 + 0.8) // 0.8-1.2
      
      const option = {
        title: {
          text: '学习效率变化曲线',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: { rotate: 45 }
        },
        yAxis: {
          type: 'value',
          name: '效率评分',
          min: 0.5,
          max: 1.5
        },
        series: [
          {
            name: '学习效率',
            type: 'line',
            data: efficiency,
            smooth: true,
            lineStyle: { color: '#ee6666', width: 3 },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(238, 102, 102, 0.3)' },
                { offset: 1, color: 'rgba(238, 102, 102, 0.1)' }
              ])
            }
          }
        ]
      }
      
      chartInstances.efficiencyTrend.setOption(option)
    }
    
    // 5. 知识资产雷达图（固定资产）
    const initKnowledgeRadarChart = (data) => {
      if (!knowledgeRadarChart.value) return
      
      chartInstances.knowledgeRadar = echarts.init(knowledgeRadarChart.value)
      
      const option = {
        title: {
          text: '知识资产雷达图',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        radar: {
          indicator: data.subjects.map(subject => ({
            name: subject,
            max: 100
          })),
          radius: '70%'
        },
        series: [
          {
            name: '掌握程度',
            type: 'radar',
            data: [
              {
                value: data.mastery,
                name: '当前掌握程度',
                itemStyle: { color: '#5470c6' },
                areaStyle: { color: 'rgba(84, 112, 198, 0.2)' }
              }
            ]
          }
        ]
      }
      
      chartInstances.knowledgeRadar.setOption(option)
    }
    
    // 6. 知识资产价值分析（固定资产）
    const initAssetValueChart = (data) => {
      if (!assetValueChart.value) return
      
      chartInstances.assetValue = echarts.init(assetValueChart.value)
      
      const option = {
        title: {
          text: '知识资产价值分析',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name),
          axisLabel: { rotate: 45 }
        },
        yAxis: [
          {
            type: 'value',
            name: '资产价值(元)',
            position: 'left'
          },
          {
            type: 'value',
            name: '增长率(%)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '资产价值',
            type: 'bar',
            yAxisIndex: 0,
            data: data.map(item => item.value),
            itemStyle: { color: '#91cc75' }
          },
          {
            name: '增长率',
            type: 'line',
            yAxisIndex: 1,
            data: data.map(item => item.growth),
            lineStyle: { color: '#ee6666' },
            itemStyle: { color: '#ee6666' }
          }
        ]
      }
      
      chartInstances.assetValue.setOption(option)
    }
    
    // 7. 投入产出分析（所有者权益）
    const initInputOutputChart = (data) => {
      if (!inputOutputChart.value) return
      
      chartInstances.inputOutput = echarts.init(inputOutputChart.value)
      
      const option = {
        title: {
          text: '投入产出分析',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        legend: {
          data: ['学习投入', '知识产出']
        },
        xAxis: {
          type: 'category',
          data: data.dates,
          axisLabel: { rotate: 45 }
        },
        yAxis: [
          {
            type: 'value',
            name: '学习投入(小时)',
            position: 'left'
          },
          {
            type: 'value',
            name: '知识产出(价值)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '学习投入',
            type: 'bar',
            yAxisIndex: 0,
            data: data.input,
            itemStyle: { color: '#5470c6' }
          },
          {
            name: '知识产出',
            type: 'line',
            yAxisIndex: 1,
            data: data.output,
            lineStyle: { color: '#ee6666' }
          }
        ]
      }
      
      chartInstances.inputOutput.setOption(option)
    }
    
    // 8. 学习债务分析（负债类）
    const initDebtAnalysisChart = (data) => {
      if (!debtAnalysisChart.value) return
      
      chartInstances.debtAnalysis = echarts.init(debtAnalysisChart.value)
      
      const option = {
        title: {
          text: '学习债务分析',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}元 ({d}%)'
        },
        series: [
          {
            name: '学习债务',
            type: 'pie',
            radius: '60%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: true,
              formatter: '{b}: ¥{c}'
            }
          }
        ],
        color: ['#ee6666', '#fac858', '#73c0de']
      }
      
      chartInstances.debtAnalysis.setOption(option)
    }
    
    // 9. 财务报表总览
    const initFinancialOverviewChart = (data) => {
      if (!financialOverviewChart.value) return
      
      chartInstances.financialOverview = echarts.init(financialOverviewChart.value)
      
      const option = {
        title: {
          text: '学习财务报表总览',
          left: 'center',
          textStyle: { fontSize: 18, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: {
          data: ['资产', '负债', '权益', '收入', '成本', '利润']
        },
        xAxis: {
          type: 'category',
          data: ['总资产', '总负债', '所有者权益', '学习收入', '时间成本', '净收益']
        },
        yAxis: {
          type: 'value',
          name: '金额(元)'
        },
        series: [
          {
            name: '资产',
            type: 'bar',
            data: [data.assets, 0, 0, 0, 0, 0],
            itemStyle: { color: '#5470c6' }
          },
          {
            name: '负债',
            type: 'bar',
            data: [0, data.liabilities, 0, 0, 0, 0],
            itemStyle: { color: '#ee6666' }
          },
          {
            name: '权益',
            type: 'bar',
            data: [0, 0, data.equity, 0, 0, 0],
            itemStyle: { color: '#91cc75' }
          },
          {
            name: '收入',
            type: 'bar',
            data: [0, 0, 0, data.income, 0, 0],
            itemStyle: { color: '#fac858' }
          },
          {
            name: '成本',
            type: 'bar',
            data: [0, 0, 0, 0, data.cost, 0],
            itemStyle: { color: '#73c0de' }
          },
          {
            name: '利润',
            type: 'bar',
            data: [0, 0, 0, 0, 0, data.profit],
            itemStyle: { color: data.profit >= 0 ? '#91cc75' : '#ee6666' }
          }
        ]
      }
      
      chartInstances.financialOverview.setOption(option)
    }
    
    const handleResize = () => {
      Object.values(chartInstances).forEach(instance => {
        instance?.resize()
      })
    }
    
    onMounted(async () => {
      await nextTick()
      await loadChartData()
      window.addEventListener('resize', handleResize)
    })
    
    onUnmounted(() => {
      Object.values(chartInstances).forEach(instance => {
        instance?.dispose()
      })
      window.removeEventListener('resize', handleResize)
    })
    
    return {
      timeDistributionChart,
      timeTrendChart,
      efficiencyKLineChart,
      efficiencyTrendChart,
      knowledgeRadarChart,
      assetValueChart,
      inputOutputChart,
      debtAnalysisChart,
      financialOverviewChart
    }
  }
}
</script>

<style scoped>
.study-charts {
  padding: 20px 0;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header span {
  font-weight: bold;
  font-size: 16px;
}

.el-card {
  margin-bottom: 20px;
}

.el-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-bottom: 2px solid #e4e7ed;
}
</style>